<template>
  <div ref="editorRef"></div>
</template>

<script setup lang="ts" name="codeEditor">
import { ref, watch } from "vue";
import * as monaco from "monaco-editor/esm/vs/editor/editor.api";
import "monaco-editor/esm/vs/basic-languages/sql/sql.contribution";
import "monaco-editor/esm/vs/basic-languages/java/java.contribution";
import { useGlobalStore } from "@/stores/modules/global";

const globalStore = useGlobalStore();
// 定义一个对 DOM 元素的引用
const editorRef = ref<HTMLDivElement | null>(null);
let editor: monaco.editor.IStandaloneCodeEditor | null = null;

const createEdit = (value: string, language: string) => {
  if (editorRef.value) {
    // 创建编辑器实例
    editor = monaco.editor.create(editorRef.value, {
      value: value,
      language: language,
      theme: globalStore.isDark ? "vs-dark" : "vs",
      fontSize: 12,
      fixedOverflowWidgets: true,
      minimap: {
        enabled: false
      },
      automaticLayout: true
    });

    // 监听编辑器内容变化
    editor.onDidChangeModelContent(() => {
      if (editor) {
        console.log("Content changed:", editor.getModel()?.getValue());
      } else {
        console.warn("editor is null");
      }
    });
  }
};
//销毁
const destroyEdit = () => {
  if (editor) {
    editor.dispose();
    editor = null;
  }
};
watch(globalStore, () => {
  if (editor) {
    editor.updateOptions({
      theme: globalStore.isDark ? "vs-dark" : "vs"
    });
  }
});
defineExpose({
  createEdit,
  destroyEdit
});
</script>

<style scoped>
/* 样式可以根据需要添加 */
</style>
